import { type ComputedRef, type Ref, nextTick, watch } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { tabbarStore } from '@/layouts/fg-tabbar/tabbar'

interface TabbarItem {
  pagePath: string
  text: string
  icon: string
  iconType: string
}

/**
 * Tabbar 同步 Hook
 * 根据当前页面路径自动同步 tabbar 选中状态
 */
export function useTabbarSync() {
  /**
   * 获取当前页面路径
   */
  const getCurrentPagePath = (): string => {
    const pages = getCurrentPages()
    if (pages.length === 0)
      return ''

    const currentPage = pages[pages.length - 1]
    return currentPage.route || ''
  }

  /**
   * 标准化路径格式，去掉开头的斜杠
   */
  const normalizePagePath = (path: string): string => {
    return path.replace(/^\/+/, '')
  }

  /**
   * 根据当前页面路径同步tabbar选中状态
   */
  const syncCurrentIndex = (tabbarList: TabbarItem[]): void => {
    const currentPath = getCurrentPagePath()
    console.log('syncCurrentIndex', currentPath, tabbarList)
    if (!currentPath || tabbarList.length === 0)
      return

    const normalizedCurrentPath = normalizePagePath(currentPath)

    // 在tabbar列表中查找匹配的索引
    const matchedIndex = tabbarList.findIndex((item) => {
      const normalizedTabbarPath = normalizePagePath(item.pagePath)
      return normalizedTabbarPath === normalizedCurrentPath
    })

    // 如果找到匹配的页面，更新选中状态
    if (matchedIndex !== -1) {
      tabbarStore.setCurIdx(matchedIndex)
      console.log(`🎯 Tabbar 同步: 当前页面 "${normalizedCurrentPath}" 匹配到索引 ${matchedIndex}`)
    }
  }

  /**
   * 初始化tabbar同步功能
   */
  const initTabbarSync = (tabbarList: Ref<TabbarItem[]> | ComputedRef<TabbarItem[]>): void => {
    // 延迟执行，确保页面路径已经更新
    const doSync = () => {
      nextTick(() => {
        syncCurrentIndex(tabbarList.value)
      })
    }

    // 页面显示时同步
    onShow(() => {
      console.log('onShow')
      doSync()
    })

    // 监听tabbar列表变化（角色切换时）
    watch(tabbarList, () => {
      console.log('watch', tabbarList)
      doSync()
    }, { immediate: true, deep: true })
  }

  /**
   * 处理tabbar点击切换
   */
  const handleTabbarSelect = (index: number, tabbarList: TabbarItem[]): void => {
    const selectedItem = tabbarList[index]
    if (selectedItem) {
      // 立即更新选中状态，避免延迟
      // tabbarStore.setCurIdx(index)
      const url = `/${selectedItem.pagePath}`
      uni.switchTab({ url })
    }
  }

  return {
    syncCurrentIndex,
    initTabbarSync,
    handleTabbarSelect,
    getCurrentPagePath,
    normalizePagePath,
  }
}
